#include <game.h>
#include <stats.h>

#include <iostream>
#include <sstream>
#include <string>

game::game( std::vector<player *> * roster ) {
	this->innings = new std::vector<inning *>();
	this->roster = roster;
	// Pre-process the game data.
	this->preProcess( roster );
	output_dbug("Created a new game.");
}

void game::preProcess( std::vector<player *> * roster ) {
	for ( unsigned int i = 0; i < roster->size(); ++i ) {

		output_dbug( roster->at(i)->getStat("name")->getValue() );

		stats * at_bats = roster->at(i)->getStat("ab");
		stats * at_1b   = roster->at(i)->getStat("1b");
		stats * at_2b   = roster->at(i)->getStat("2b");
		stats * at_3b   = roster->at(i)->getStat("3b");

		std::string atBats = at_bats->getValue();
		std::string at1B   = at_1b->getValue();
		std::string at2B   = at_2b->getValue();
		std::string at3B   = at_3b->getValue();

		int AB = atoi(atBats.c_str());
		int FB = atoi(at1B.c_str()  );
		int SB = atoi(at2B.c_str()  );
		int TB = atoi(at3B.c_str()  );

		if (
			AB > 0 &&
			FB >= 0 &&
			SB >= 0 &&
			TB >= 0
		) {
			// HELL YEAH
			double FB_pct = (FB/AB);
			double SB_pct = (SB/AB);
			double TB_pct = (TB/AB);

			stats * fB_pct = new stats();
			stats * sB_pct = new stats();
			stats * tB_pct = new stats();

			std::ostringstream ss;

			ss << std::dec << FB_pct;
			fB_pct->setName( "_1b_pct" );
			fB_pct->setValue( ss.str() );
			ss.str("");

			ss << std::dec << SB_pct;
			sB_pct->setName( "_2b_pct" );
			sB_pct->setValue( ss.str() );
			ss.str("");

			ss << std::dec << TB_pct;
			tB_pct->setName( "_3b_pct" );
			tB_pct->setValue( ss.str() );
			ss.str("");

			roster->at(i)->addStat( fB_pct );
			roster->at(i)->addStat( sB_pct );
			roster->at(i)->addStat( tB_pct );


		} else {
			output_msg( "You're missing AB / 1B / 2B / 3B stats!" );
			throw _badbeef;
		}
	}
}

void game::run() {
	/*
	 * Hey there, Paul here.
	 *
	 * We're not simulating an opposing team. That would
	 * be very hard, and start blowing time on stuff we
	 * really don't need at all. 
	 * 
	 * If we're in a no-hit situation, we'll be sure to use that
	 * as an overtime situation, but there's no way for the other
	 * team to score. Lame, I know.
	 * 
	 * Well, let's get down to basics. There's going to be a huge
	 * profile being dumped. Let's go slowly here.
	 * 
	 */
	this->score = 0; // We're going to start out with no hits.

	while ( this->innings->size() < 9 || score == 0 ) {
		// we're in here because we're less then 9 innings,
		// or we're at a 0 score, OR we're both.
		inning * now = new inning( this->roster );
		now->run();
		int inning_score = now->get_score();
		this->innings->push_back( now );
		this->score += inning_score;
	}

	// let's post-game.

	int result = 0;

	for ( unsigned int i = 0; i < this->innings->size(); ++i ) {
		inning * now = this->innings->at(i);
		result += now->get_score();
	}

	std::stringstream ss;
	ss << "score:" << result;
	std::string hitz = ss.str();

	output_msg( hitz );
}




